package cn.uyunsky.platform.config.loader;

import java.util.List;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;

import cn.uyunsky.platform.config.ConfigBeanInterface;
import cn.uyunsky.platform.config.ConfigLoader;
import cn.uyunsky.platform.config.bean.sqltemplate.SqlTemplateBean;

public class SqlTemplateLoader implements ConfigLoader {

	// 定义节点名
	private static final String ID = "id";
	private static final String ELEMENT_SQL = "sql";


	@Override
	public ConfigBeanInterface loadConfig(Resource resource, Class<? extends ConfigBeanInterface> clazz)
			throws Exception {
		SqlTemplateBean config = new SqlTemplateBean();

		// 创建解析工厂
		SAXReader reader = new SAXReader();
		Document doc = reader.read(resource.getInputStream());
		Element root = doc.getRootElement();

		List<?> dblist = root.elements(ELEMENT_SQL);
		for (int j = 0; j < dblist.size(); j++) {
			Element dbinfo = (Element) dblist.get(j);
			String sqlid = dbinfo.attributeValue(ID);
			String sqlcontent = dbinfo.getTextTrim();

			if (config.containsKey(sqlid)) {
				throw new Exception("sql模板中已存在id为[" + sqlid + "]的配置");
			}
			config.put(sqlid, sqlcontent);
		}
		return config;
	}

}
